package main

import (
	"fmt"
	"net"
	"runtime"
	"strings"
	"time"
)

func main() {
	address := "127.0.0.1:9999"
	listen, err := net.Listen("tcp", address)
	if err != nil {
		fmt.Printf("net.Listen err=%v\n", err)
		return
	}
	runtime.GOMAXPROCS(1)
	fmt.Printf("服务器:[%v] 已开启监听\n", address)
	for {
		conn, err2 := listen.Accept()
		if err2 != nil {
			fmt.Printf("listen.Accept err=%v\n", err2)
			return
		}
		fmt.Printf("客户端:[%v] 已连接\n", conn.RemoteAddr().String())
		go func(conn net.Conn) {
			clientName := conn.RemoteAddr().String()
			for {
				//接收客户端发送过来的数据
				buffer := make([]byte, 1024)
				i, err3 := conn.Read(buffer)
				if err3 != nil {
					fmt.Printf("客户端:[%v] 已退出\n", clientName)
					return
				}
				remoteData := strings.Trim(string(buffer[:i]), "\n")
				fmt.Printf("客户端:[%v] 发送的数据为:\"%v\"\n", clientName, remoteData)

				//返回数据给客户端
				data := remoteData + fmt.Sprintf("%d", time.Now().UnixNano())
				_, err := conn.Write([]byte(data))
				if err != nil {
					return
				}
			}
		}(conn)
	}

}
